<template>
    <main class="mx-2 sm:w-full md:w-100">
        <div class="flex items-center justify-between">
            <h3>大乐透手机版（祝您好运！）</h3>
            <div class="lg:hidden">
                <RefreshButton></RefreshButton>
                <ThemeSwitch class="mx-1"></ThemeSwitch>
            </div>
        </div>
        <el-tabs type="border-card" class="tabs-small">
            <el-tab-pane label="选号助手">
                <div class="mb-2 flex items-center justify-between">
                    <div>本期：{{ currentDrawNum }}</div>
                    <ComClock class="me-3"></ComClock>
                </div>
                <div class="w-90">
                    <div class="flex items-center pb-2 mb-3 border-b-1 border-b-solid border-gray-200">
                        <div class="w-5 text-end pr-2">#</div>
                        <div class="w-40">号码</div>
                        <div class="w-10 ml-2">和值</div>
                        <div class="w-20">操作</div>
                    </div>
                    <div class="flex items-center mb-1">
                        <div class="w-5 text-end pr-2">-</div>
                        <div class="w-40 ps-2">{{ lastDrawInfo.lotteryDrawResult }}</div>
                        <div class="w-10">
                            {{lastDrawInfo.lotteryDrawResult.split(' ').reduce((a, b) => parseInt(a)
                                + parseInt(b))}}
                        </div>
                        <div class="w-20">{{ lastDrawInfo.lotteryDrawNum }}开奖</div>
                    </div>
                    <div class="h-83 overflow-y-auto" v-show="list.length > 0">
                        <div class="flex items-center mt-1" v-for="(item, idx) of list" :key="idx">
                            <div class="w-5 text-end pr-2">{{ idx + 1 }}</div>
                            <div class="w-40"><el-input size="small" clearable v-model="list[idx]" /></div>
                            <div class="w-10 ml-2">{{list[idx].split(' ').reduce((a, b) => parseInt(a) + parseInt(b))}}
                            </div>
                            <div class="w-20">
                                <el-button-group size="small">
                                    <el-button type="danger" @click="onDeleteRow(idx)">删除</el-button>
                                </el-button-group>
                            </div>
                        </div>
                    </div>
                </div>
                <el-empty v-show="list.length == 0">请点击【机选】或【解析AI选号】按钮添加号码。</el-empty>
                <div class="text-xs text-gray-400 my-2">{{ stat.count }} 注 {{ stat.total }} 元</div>
                <div class="flex items-center justify-between">
                    <el-button-group size="small">
                        <el-button type="danger" @click="list = []">清空</el-button>
                        <el-button type="primary" @click="onChooseAuto()">机选</el-button>
                        <el-tooltip content="机选 10 注" placement="top-start">
                            <el-button type="primary" @click="onChooseAuto(10)">x10</el-button>
                        </el-tooltip>
                        <el-tooltip content="从机选号码中再次随机选择号码" placement="top-start">
                            <el-button type="primary" @click="onChooseAutoBetter()">优选</el-button>
                        </el-tooltip>
                        <el-button type="primary" @click="aiDialogInfo.visible = true">解析 AI 选号</el-button>
                    </el-button-group>
                    <el-button-group size="small">
                        <el-button type="info" @click="onCopy()">复制</el-button>
                        <el-button type="info" @click="onSave()">保存</el-button>
                    </el-button-group>
                </div>
            </el-tab-pane>
            <el-tab-pane label="历史数据">
                <HistoryView embedded></HistoryView>
            </el-tab-pane>
            <el-tab-pane label="中奖计算">
                <RewardsCalc></RewardsCalc>
            </el-tab-pane>
        </el-tabs>
    </main>

    <el-drawer v-model="aiDialogInfo.visible" size="90%" title="AI 选号">
        <div class="mb-1">
            <AiProviderSelect v-model="aiDialogInfo.provider"></AiProviderSelect>
        </div>
        <el-input type="textarea" v-model="aiDialogInfo.text" placeholder="请粘贴 AI 选号内容" :rows="20"></el-input>
        <template #footer>
            <el-button-group size="small">
                <el-button type="primary" @click="handleImport(aiDialogInfo.text)">立即解析</el-button>
                <el-button type="warning" @click="aiDialogInfo.text = ''">清空</el-button>
                <el-button type="info" @click="aiDialogInfo.visible = false">关闭</el-button>
            </el-button-group>
        </template>
    </el-drawer>
</template>

<script setup>
import HistoryView from './HistoryView.vue';
import RewardsCalc from './components/RewardsCalc.vue';
import RefreshButton from './components/RefreshButton.vue';
import ComClock from './components/com-clock/ComClock.vue';
import AiProviderSelect from '@/components/aiprovider-select/AiProviderSelect.vue';
import ThemeSwitch from '@/components/ThemeSwitch.vue';
import { ref } from 'vue';
import DltDataModel from '@/model/DltDataModel';
import DltOrderModel from '@/model/DltOrderModel';
import FsDriver from '@/model/FsDriver';
import { copyText } from '@/utils/Utils';
import { ElMessage } from 'element-plus';

const fsDriver = new FsDriver();
const dltDataModel = new DltDataModel();
const dltOrderModel = new DltOrderModel();
const aiDialogInfo = ref({ visible: false, text: '', provider: 'DeepSeek' });
const dataset = [...dltDataModel.getDataSource()];
const lastDrawInfo = dataset.length > 0 ? dataset[0] : {};
const currentDrawNum = ref(parseInt(lastDrawInfo.lotteryDrawNum) + 1);
const list = ref([]);
const isAutoList = ref(true);
const stat = ref({
    count: 0,
    total: 0,
});
const formData = ref({
    issue: currentDrawNum,
    DrawalInfo: lastDrawInfo,
    AiList: {
        Nami: [],
        DeepSeek: [],
    },
    AutoList: [],
    BetterAutoList: [],
})

const handleImport = (text) => {
    list.value = dltOrderModel.parseAiText(text, aiDialogInfo.value.provider.toLowerCase());
    handleStat();
    aiDialogInfo.visible = false;
    formData.value.AiList[type] = list.value;
}
const onDeleteRow = (idx) => {
    list.value.splice(idx, 1);
    handleStat();
}
const handleStat = () => {
    if (list.value.length == 0) {
        return;
    }
    stat.value.count = list.value.length;
    stat.value.total = stat.value.count * 2;
}
const onCopy = () => {
    copyText(list.value.join('\n'));
    ElMessage.success('复制成功');
}

const onSave = () => {
    if (list.value.length == 0) {
        ElMessage.error('内容不能为空');
        return;
    }
    fsDriver.save('temp-order2', JSON.stringify(formData.value));
}
/**
 * 机选一注
 */
const onChooseAuto = (count = 1) => {
    isAutoList.value = true;
    let nums = [], n = count == 1 ? count : (count - list.value.length);
    while (n > 0) {
        nums = dltOrderModel.getRandomNums7('columns', 2, lastDrawInfo.lotteryDrawResult);
        list.value.push(nums[0].join(' ') + ' ' + nums[1].join(' '));
        n--;
    }
    formData.value.AutoList = list.value;
    handleStat();
}

/**
 * 优选（在机选号码里面继续机选）
 */
const onChooseAutoBetter = () => {
    if (formData.value.AutoList.length == 0) {
        ElMessage.error('请先选择机选的号码');
        return;
    }
    if (isAutoList.value) {
        list.value = [];
    }
    isAutoList.value = false;
    let nums = [], count = formData.value.AutoList.length;
    let n = count - list.value.length;
    while (n > 0) {
        nums = dltOrderModel.getRandomNums7('columns', 2, formData.value.AutoList);
        list.value.push(nums[0].join(' ') + ' ' + nums[1].join(' '));
        n--;
    }
    formData.value.BetterAutoList = list.value;
    handleStat();
}
</script>